const express = require('express')
const createError = require('http-errors')
const crypto = require('crypto')
const path = require('path')

const managerService = require('../service/managerService')
const bannerService = require('../service/bannerService')
//const multer  = require('multer')
const upload = require('../util/upload') //multer({ storage: path.join(__dirname, './public/upload') })
const moment = require('moment')

var router = express.Router()

// 注册
router.get('/register', (req, res, next) => {
  let body = req.query
  body.roleid = 1
  managerService.add(body, function(result){
    console.log(result.model)
  }, function (error) {
    res.render('error', { tip: error.msg })
  })
})

// 登录页面
router.get('/login', (req, res, next) => {
  res.render('login', { title: '管理员登录' })
})

// 登录验证
router.post('/login', (req, res, next) => {
  let body = req.body
  if(body) {
    managerService.findone({
      account: body.account,
      passwd: crypto.createHash('md5').update(body.passwd, 'utf8').digest('hex')
    }, function (result) {
      if(result.code === 1 && result.model != null) {
        // 通过
        req.session.SManagerAccount = result.model.account
        req.session.SManagerPasswd = result.model.passwd
        // 存到客户端
        res.cookie('account', result.model.account);
        res.cookie('passwd', result.model.passwd);
        res.redirect('/admin/index')
      } else {
        res.render('login', { title: '管理员登录', tip: '用户名或密码错误！' })
      }
    }, function (error) {
      res.render('error', { tip: error.msg })
    })
  }
})

// 部分页面需要验证登录
router.use((req, res, next) => {
  // 验证session
  let where = {
    account: req.session.SManagerAccount || req.cookies.account || '',
    passwd: req.session.SManagerPasswd || req.cookies.passwd || ''
  }
  managerService.findone(where, function (result){
    if(result.code === 1 && result.model != null) {
      req.session.SManagerAccount = result.model.account
      req.session.SManagerPasswd = result.model.passwd
      req.session.SManager = JSON.stringify(result.model)
      // 存到客户端
      res.cookie('account', result.model.account);
      res.cookie('passwd', result.model.passwd);
      res.cookie('CManager', JSON.stringify(result.model))
      next()
    } else {
      res.redirect('/admin/login')
    }
  }, function (error) {
      res.render('error', { tip: error.msg })
  })
  
})

// 个人中心首页
router.get('/', (req, res, next) => {
  let currentManager = JSON.parse(req.session.SManager || req.cookies.CManager)
  res.render('index', { title: '管理中心首页', active: 'index', username: currentManager.realname || '', MemberCount: 0, GoodsCount: 0, MessageCount: 0, MoneyCount: 0 })
})

router.get('/index', (req, res, next) => {
  let currentManager = JSON.parse(req.session.SManager || req.cookies.CManage)
  res.render('index', { title: '管理中心首页', active: 'index', username: currentManager.realname || '', MemberCount: 0, GoodsCount: 0, MessageCount: 0, MoneyCount: 0 })
})

// 退出登录
router.get('/logout', (req, res) => {
  // 清session
  req.session.SManagerAccount = ''
  req.session.SManagerPasswd = ''
  req.session.SManager = ''
  // 清cookie
  res.cookie('account', '')
  res.cookie('passwd', '')
  res.cookie('CManager', '')
  res.redirect('/admin/login')
})

// 幻灯片管理
router.get('/banners', (req, res) => {
  var body = req.query
  bannerService.getpagelist(body.pagesize, body.pageindex,function(result) {
    if(result.code === 1 && result.model != null) {
      res.render('banners', { banners: result.model, active: 'banners' })
    }
  }, function (error) {
     res.render('error', { tip: error.model.message })
  })
})

// 幻灯片添加
router.get('/banners/add', (req, res) => {
  res.render('banner_add', { active: 'banners' })
})
router.post('/banners/add', upload.single('image'), (req, res) => {
  var body = req.body;
  if(body) {
    body.filepath = '/'+req.file.path.replace(/\\/g, '/');
    body.type = 1;
    body.fid = 0;
    bannerService.add(body, function (result) {
      if(result.code == 1){
        // ajax异步请求的，需传json到前台，在页面上处理
        res.json({code: result.code, url: '/admin/banners'})
      }
    }, function (error) {
      res.json({code: -1, msg: error.model.message })
    })
  }
})

// 幻灯片删除
router.post('/banners/delete', function (req, res) {
  let ids = req.body['ids[]'] || []
  if(typeof(ids) == 'string') {
    ids = ids.split(',')
  }
  bannerService.deletebyids(ids, function (result) {
    if(result.code == 1){
      // ajax异步请求的，需传json到前台，在页面上处理
      res.json({code: result.code, url: '/admin/banners'})
    }
  }, function (error) {
    res.json({code: -1, msg: error.model.message })
  })
})

// 幻灯片修改
router.get('/banners/edit', function (req, res) {
  let id = req.query.id
  bannerService.findone({id: id}, function (result) {
    if(result.code == 1) {
      res.render('banner_edit', { active: 'banners', model: result.model })
    }
  }, function (error) {
    res.render('error',  { tip: error.model.message })
  })
})

router.post('/banners/edit', function (req, res) {
  let model = req.body
  bannerService.update(model, function (result) {
    if(result.code == 1) {
      res.redirect('/admin/banners')
    }
  }, function (error) {
    res.render('error',  { tip: error.model.message })
  })
})


// 404处理
router.use((req, res, next) => {
  next(createError(404))
  //res.send('Sorry this path is not found, 404 process is working!')
})

// 错误处理
router.use(function(err, req, res,next) {
  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = router